#!/usr/bin/env python
# coding:utf-8
# File Name    : cgroup-exporter.py
# Created Time : 2025-05-10 07:39:53
# Update Time  : 2025-05-10 15:13:53
# Author       : moshan
# mail         : mo_shan@yeah.net
# Version      : 1.0
# Function     : cgroup exporter

import pymysql,sys
from flask import Flask, Response

app = Flask(__name__)

@app.route('/metrics')

def metrics():

    monitor_user = 'xxxx'

    monitor_pass = 'xxxxxx'

    monitor_host = '192.168.1.1'

    monitor_port = 4000

    monitor_db = 'tdb_cg_monitor'

    if sys.argv[1] == "oltp" :

        monitor_user = 'xxxx'

        monitor_pass = 'xxxxxx'

        monitor_host = '192.168.1.1'

        monitor_port = 4000

    rtime = 60

    wtime = 60

    db = pymysql.connect(monitor_host, monitor_user, monitor_pass, monitor_db, monitor_port, read_timeout = rtime, write_timeout = wtime)

    cursor = db.cursor()

    #cursor.execute('select rshost,rsport,isotype,mvalue,isovalue from tb_monitor_cgroup_info where a_time > date_add(now(), INTERVAL - 1 MINUTE);')
    cursor.execute('select b.rshost,b.rsport,b.isotype,b.mvalue,b.isovalue,a.rsrole from tb_monitor_cgroup_info b left join tb_mysql_role a on a.rsport = b.rsport and a.rshost = b.rshost where b.a_time > date_add(now(), INTERVAL - 1 MINUTE);')

    data = cursor.fetchall()

    output = []

    for info in data :

        tmp = """rshost = "{}", rsport = "{}", isotype = "{}",isovalue = "{}",rsrole = "{}" """.format(info[0],info[1],info[2],info[4],info[5])

        output.append("cgroup_monitor_info{" + tmp + "} " + str(info[3]))

    cursor.close()

    db.close()

    return Response('\n'.join(output), mimetype = 'text/plain')


if __name__ == '__main__' :

    app.run(host = '0.0.0.0', port = 5000, debug = True)

#*/1 * * * * cd /opt/soft/cgroup && flock --wait 5 -x lock/cg_export.lock -c "/opt/soft/rpc_for_monitor/py37env/bin/python /opt/soft/cgroup/cgroup-exporter.py oltp"
